package com.xbn.netty.coder2;

import com.xbn.netty.codec.StudentPOJO;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author XBN
 * @date 2020/10/19 13:33
 * @email 78742541@qq.com
 */

public class NettyServerHandler extends SimpleChannelInboundHandler<MyStudent.MyMessage> {



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyStudent.MyMessage msg) throws Exception {
        MyStudent.MyMessage.DataType dataType = msg.getDataType();
        if(dataType==MyStudent.MyMessage.DataType.StudentType) {
            System.out.println("接收到数据类型为Student" + "id=" + msg.getStudent().getId() + ",name=" + msg.getStudent().getName());
        }
        else if(dataType==MyStudent.MyMessage.DataType.WorkerType)
        {
            System.out.println("接收到数据类型为Worker，" + "id=" + msg.getWorker().getAge() + ",name=" + msg.getWorker().getName());
        }
        else {
            System.out.println("其它类型");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端，本条消息是服务器给你的响应"
                ,CharsetUtil.UTF_8)
        );
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
